package netwprk2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    // 客户端用普通的Socket即可
    private Socket socket;

    // 构造方法指定IP和端口号
    public TcpEchoClient (String serverIp, int port) throws IOException {
        socket = new Socket(serverIp, port);
    }

    public void start () {
        System.out.println("连接服务器成功.");

        try(InputStream inputStream = socket.getInputStream()) {
            try (OutputStream outputStream = socket.getOutputStream()) {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    // 1. 接收用户输入
                    System.out.println("->");
                    String request = scanner.next();
                    // 2. 构造数据发送到服务器
                    PrintWriter writer = new PrintWriter(outputStream);
                    // 写数据
                    writer.println(request);
                    // 强制刷新缓冲区，如果不刷新，客户端可能不能及时收到响应
                    writer.flush();
                    // 3. 接收服务器响应的数据
                    Scanner resScanner = new Scanner(inputStream);
                    String response = resScanner.next();
                    // 4. 解析响应并打印
                    System.out.printf("request : %s, response : %s\n", request, response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
